// pages/stores/stores.js
const util = require('../../utils/util.js')
const app = getApp()
let storesInitDate = new Date(+new Date() + 24 * 60 * 60 * 1000)  //默认预约明天
let curDateStr = storesInitDate.getFullYear() + '-' + app.globalData.addZero(storesInitDate.getMonth() + 1) + '-' + app.globalData.addZero(storesInitDate.getDate())
Page({
  /**
   * 页面的初始数据
   */
  data: {
    /*  */
    showOpenSetting: true,  //打开openSetting
    showNoDataIcon: false,
    userInfo_chezhu: null,
    /*  */
    latitude: '',
    longitude: '',
    //当前日期
    nowDate: curDateStr,
    //选中的日期
    selectedDate: curDateStr,
    selectedTime: '09:00',
    //显示预约时间弹层
    showStorePop: true,
    /*  */
    timestep: '',  //时段
    /* 请求参数 */
    storeArgs: {
      cardNo: '',
      latLng: '',
      page: 1,
      pageSize: 10
    },
    storeData: [],
    /* 未授权获取位置信息 */
    positionHide: false,
    /* 平台预约接口参数 */
    appointArgs: {
      cardNo: '',  //卡号
      arriveTime: '',  //预计到达时间
      mobile: '',  //手机
      storeId: '',  //店铺Id
      storeProject: '', //预约项目
      name: '',  //预约人
      status: '0'  //状态：0、新增，1、同意，2、拒绝
    }
  },
  /* 获取预约人姓名 */
  getYYname: function (e) {
    this.setData({
      'appointArgs.name': e.detail.value
    })
  },
  /* 选择时段 */
  setTimeStepValue: function (e) {
    this.setData({
      timestep: e.detail.value
    })
  },
  /* 设置所选日期 */
  setSelectedDate: function (e) {
    //console.log(e.detail.value)
    let st = +new Date(this.data.nowDate)
    let et = +new Date(e.detail.value)
    if (et < st) {
      wx.showModal({
        title: '提示',
        content: '所选的使用日期不能早于当天',
        showCancel: false,
        confirmColor: app.globalData.modalConfirmColor,
        confirmText: '知道了'
      })
      return
    }
    /*  */
    this.setData({
      selectedDate: e.detail.value
    })
  },
  /* 电话预约 */
  makeCall: function (e) {
    let { info } = e.currentTarget.dataset
    if (info.appointmentStatus != '0') {
      wx.showToast({
        icon: 'none',
        title: '预约中...'
      })
      return
    }
    wx.makePhoneCall({
      phoneNumber: '' + info.mobile,
      success: () => { },
      fail: () => { }
    })
  },
  /* 设置所选时间 */
  setSelectedTime: function (e) {
    this.setData({
      selectedTime: e.detail.value
    })
  },
  /* 获取支持的商户 */
  getSupportStore: function (isRefresh) {
    this.setData({
      showNoDataIcon: false
    })
    if (isRefresh) {
      let tmpStoreData = this.data.storeData
      let pageNum = this.data.storeArgs.page * 1
      pageNum = 1
      tmpStoreData.splice(0, tmpStoreData.length)
      this.setData({
        storeData: tmpStoreData,
        'storeArgs.page': pageNum
      })
    }
    /* latLng */
    this.setData({
      'storeArgs.latLng': this.data.latitude + ',' + this.data.longitude
    })
    /* cardNo */
    wx.showLoading({
      title: '获取支持商户',
    })
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.Url + '/wx/getSupportStore',
        method: 'POST',
        header: this.data.userInfo_chezhu.header,
        data: util.json2Form(this.data.storeArgs),
        success: res => {
          console.log(res)
          //判断token是否过期
          if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
          if (res.data.code == '1') {
            /* 无数据 */
            if (!res.data.body.data.length) {
              if(!this.data.storeData.length&&this.data.userInfo_chezhu.isOpenScopePos){
                this.setData({
                  showNoDataIcon: true
                })
              }
              return resolve()
            }
            let tmpStoreData = this.data.storeData
            res.data.body.data.forEach(item => {
              item.appointName = item.appointmentStatus == '0' ? '平台预约' : '预约中'  //
              item.distance = this.data.positionHide ? '' : this.setDistance(item.distance)
              tmpStoreData.push(item)
            })
            let pageNum = this.data.storeArgs.page * 1
            pageNum += 1
            this.setData({
              storeData: tmpStoreData,
              'storeArgs.page': pageNum
            })
            resolve()
          } else {
            wx.showToast({
              icon: 'none',
              title: ''+res.data.msg
            })
            if(!this.data.storeData.length&&this.data.userInfo_chezhu.isOpenScopePos){
              this.setData({
                showNoDataIcon: true
              })
            }
            reject()
          }
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            icon: 'none',
            title: '获取数据失败'
          })
          if(!this.data.storeData.length&&this.data.userInfo_chezhu.isOpenScopePos){
            this.setData({
              showNoDataIcon: true
            })
          }
          reject()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  /* 距离 */
  setDistance: function (dis) {
    let distance = dis * 1
    return distance < 1000 ? distance + 'm' : (distance / 1000).toFixed(1) + 'km'
  },
  /* 平台预约 */
  testPTYY: function (e) {
    //console.log(e.currentTarget.dataset)
    let info = e.currentTarget.dataset.info
    console.log(info)
    /*  */
    if (info.appointmentStatus != '0') {
      wx.showToast({
        icon: 'none',
        title: '预约中...'
      })
      return
    }
    /*  */
    this.setData({
      'appointArgs.cardNo': this.data.storeArgs.cardNo,  //卡号
      'appointArgs.arriveTime': app.globalData.dateStrFormat12(this.data.selectedDate + '-' + this.data.timestep),  //预计到达时间
      'appointArgs.mobile': this.data.userInfo_chezhu.mobile,  //手机
      'appointArgs.storeId': info.id,
      showStorePop: false
    })
    //console.log(this.data.appointArgs)
  },
  /* 关闭预约弹层 */
  cancelPTYY: function () {
    this.setData({
      showStorePop: true
    })
  },
  /* 提交预约 */
  submitPTYY: function () {
    if (!this.data.appointArgs.name) {
      wx.showToast({
        icon: 'none',
        title: '请填写预约人姓名'
      })
      return
    }
    if (!this.data.timestep) {
      wx.showToast({
        icon: 'none',
        title: '请选择使用时段'
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '确定要提交预约吗？',
      success: res => {
        //console.log(res)
        this.setData({
          'appointArgs.arriveTime': app.globalData.dateStrFormat12(this.data.selectedDate) + '-' + this.data.timestep  //到店时间
        })
        //console.log(this.data.appointArgs)
        if (res.confirm) {
          this.insertStoreAppointment().then(() => {
            return this.getSupportStore(true)
          }).then(() => {
            wx.showToast({
              title: '提交预约成功'
            })
            this.setData({
              showStorePop: true
            })
          })
        }
      }
    })
  },
  /* 提交预约接口 */
  insertStoreAppointment: function () {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '提交预约'
      })
      wx.request({
        url: app.globalData.Url + '/wx/insertStoreAppointment',
        method: 'POST',
        header: this.data.userInfo_chezhu.header,
        data: util.json2Form(this.data.appointArgs),
        success: res => {
          console.log(res)
          //判断token是否过期
          if(app.globalData.check_token(res.data.code))return new Promise((resolve,reject)=>{})
          if (res.data.code == '1') {
            resolve()
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg + ''
            })
            reject()
          }
        },
        fail: err => {
          console.log(err)
          wx.showToast({
            icon: 'none',
            title: '添加预约失败'
          })
          reject()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  /* 显示商家位置 */
  showStoreMap: function (e) {
    if (!this.data.userInfo_chezhu.isOpenScopePos) {
      return
    }
    //console.log(e.currentTarget.dataset)
    let { pos, info } = e.currentTarget.dataset
    //
    let latLng = info.latLng.split(',')
    wx.openLocation({
      latitude: latLng[0]*1,
      longitude: latLng[1]*1,
      scale: 18
    })
    // wx.navigateTo({
    //   url: '/pages/store-pos/store-pos',
    //   success: res => {
    //     res.eventChannel.emit('show-store-pos', {
    //       info: info,
    //       pos: info.latLng
    //     })
    //   }
    // })
  },
  /* 获取openSetting结果 */
  getOpenSettingData: function (e) {
    console.log(e)
    let { authSetting } = e.detail
    if (authSetting['scope.userLocation']) {
      this.setData({
        showOpenSetting: true,
        'userInfo_chezhu.isOpenScopePos': true
      })
      //信息存缓存
      wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
      //
      this.getDataByUserLocation()
    } else {
      wx.showToast({
        icon: 'none',
        title: '请开启位置授权'
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    /*  */
    this.getDataByUserLocation()
  },
  /*  */
  getDataByUserLocation: function () {
    //获取用户信息
    this.setData({
      userInfo_chezhu: app.globalData.get_userInfo()
    })
    //
    if (this.data.userInfo_chezhu.isOpenScopePos) {
      app.globalData.getLocation().then(res => {
        //console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        /*  */
        let eventChannel = this.getOpenerEventChannel()
        /*  */
        eventChannel.on('open-stores-page', data => {
          //console.log(data)
          this.setData({
            'storeArgs.cardNo': data.cardNo,
            'appointArgs.storeProject': data.cardName
          })
          /*  */
          !this.data.storeData.length&&this.getSupportStore()
        })
      }).catch(err => {
        this.setData({
          showOpenSetting: false
        })
      })
    } else {
      this.setData({
        showOpenSetting: false
      })
      //
      wx.authorize({
        scope: 'scope.userLocation',
        success: res => {
          console.log(res)
          if (res.errMsg === 'authorize:ok') {
            //
            this.setData({
              showOpenSetting:true,
              'userInfo_chezhu.isOpenScopePos': true
            })
            //信息存缓存
            wx.setStorageSync('userInfo_chezhu', this.data.userInfo_chezhu)
            //
            app.globalData.getLocation().then(res => {
              //console.log(res)
              this.setData({
                latitude: res.latitude,
                longitude: res.longitude
              })
              /*  */
              let eventChannel = this.getOpenerEventChannel()
              /*  */
              eventChannel.on('open-stores-page', data => {
                //console.log(data)
                this.setData({
                  'storeArgs.cardNo': data.cardNo,
                  'appointArgs.storeProject': data.cardName
                })
                /*  */
                !this.data.storeData.length&&this.getSupportStore()
              })
            }).catch(err => {
              this.setData({
                showOpenSetting: false
              })
            })
          } else {
            this.setData({
              showOpenSetting: false
            })
            wx.hideLoading()
          }
        },
        fail: err => {
          this.setData({
            showOpenSetting: false
          })
          wx.hideLoading()
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getSupportStore(true).then(() => {
      wx.stopPullDownRefresh({
        complete: (res) => { }
      })
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getSupportStore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})